<template>
  <el-upload
    ref="uploadImage"
    class="avatar-uploader"
    action
    :data="data"
    :accept="imgArr.join(',')"
    :show-file-list="false"
    :http-request="Upload"
    :on-change="handlerOnChange"
  >{{writing}}</el-upload>
</template>
<script>
import { getOSS } from "@/api";
import { UPLOAD_VALUE } from "@/utils/common";

export default {
  name: "upload",
  props: {
    image: {
      type: String
    },
    imgType: {
      type: [String, Number],
      default: UPLOAD_VALUE.MEMBER_AVATAR
    },
    writing: {
      type: String,
      default: "上传图片"
    }
  },
  data() {
    return {
      data: {
        name: "",
        key: "",
        policy: "",
        OSSAccessKeyId: "",
        success_action_status: 200,
        signature: ""
      },
      imgArr: [
        "image/jpg",
        "image/jpeg",
        "image/png",
        "jpg",
        "jpeg",
        "gif",
        "png",
        "bmp"
      ],
      xhr: new XMLHttpRequest()
    };
  },
  created() {},
  methods: {
    async Upload(file) {
      console.log("上传图像");
      const ossData = new FormData();
      const name =
        file.file.uid + Math.floor(Math.random() * 100) + file.file.name;
      let OSSURL = "";
      let PATH = "";
      await getOSS({ folder: this.imgType }).then(res => {
        const data = res;
        ossData.append("name", name);
        ossData.append("key", `${data.dir}${name}`);
        ossData.append("policy", data.policy);
        ossData.append("OSSAccessKeyId", data.accessid);
        ossData.append("success_action_status", 200);
        ossData.append("signature", data.signature);
        ossData.append("callback", data.callback);
        ossData.append("file", file.file, name);
        OSSURL = data.host;
        PATH = data.dir;
      });
      this.xhr.open("post", OSSURL, true);
      this.xhr.onload = res => {
        if (res.target.status === 200) {
          setTimeout(() => {
            this.$emit("image-success", {
              url: `${PATH}${encodeURIComponent(name)}`
            });
            this.$emit(
              "update:image",
              `${OSSURL}/${PATH}${encodeURIComponent(name)}`
            );
            // this.$message.success("上传成功!");
          });
        } else {
          this.$message.error("图片上传失败，请重新上传！");
        }
      };
      this.xhr.send(ossData);
    },
    handlerOnChange(file) {
      let size = file.size / 1024 / 1024 / 2;
      if (size > 8) {
        this.$message.error("图片大小必须小于8M");
        return false;
      }
      if (!this.imgArr.includes(file.raw.type)) {
        this.$message.error(`不支持${file.raw.type}的上传格式`);
        return false;
      }
    }
  }
};
</script>
<style scoped>
</style>
